// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { createPinia } from 'pinia'
import './assets/styles/global.css'

// 创建 Vue 应用
const app = createApp(App)

// 使用 Pinia 状态管理
const pinia = createPinia()
app.use(pinia)

// 使用 Vuex store (如果仍然需要)
app.use(store)

// 使用 Vue Router
app.use(router)

// 页面关闭前断开 WebSocket 连接
window.addEventListener('beforeunload', () => {
  try {
    const { useWebsocketStore } = require('@/store/websocket')
    const websocketStore = useWebsocketStore()
    websocketStore.disconnectWebSocket()
  } catch (error) {
    console.error('Error disconnecting WebSocket on unload:', error)
  }
})

// src/main.js (在 app.mount('#app') 之前添加)
// 检查是否已登录，如果已登录则建立WebSocket连接
const initWebsocketConnection = async () => {
  const token = localStorage.getItem('token')
  if (token) {
    try {
      // 动态导入避免循环依赖
      const { useWebsocketStore } = await import('@/store/websocket')
      const websocketStore = useWebsocketStore()
      websocketStore.connectWebSocket(token)
    } catch (error) {
      console.error('Failed to initialize WebSocket connection:', error)
    }
  }
}

// 调用初始化函数
initWebsocketConnection()

// 挂载应用
app.mount('#app')
